package com.fsc.comadapoc1.application
{
	import com.fsc.comadapoc1.domain.PortfolioModel;
	import com.fsc.comadapoc1.entities.Portfolio;
	import com.fsc.comadapoc1.enums.GUID;
	import com.fsc.comadapoc1.events.PortfolioSearchEvent;
	import com.fsc.comadapoc1.utils.PortfolioUtil;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.remoting.RemoteObject;
	import mx.utils.ArrayUtil;
	
	import org.spicefactory.lib.util.ArrayUtil;

	[Event(name="searchComplete",type="com.fsc.comadapoc1.events.PortfolioSearchEvent")]
	[ManagedEvents(names="searchComplete")]
	public class SearchPortfoliosCommand extends EventDispatcher
	{
		public var searchTerm:String;
		
		[Inject(id="portfolioService")]
		public var service:RemoteObject;
		
		/**
		 * Contains objects to manage portfolios
		 */ 
		[Inject]
		[Bindable]
		public var model:PortfolioModel;
		
		private var pendingSearchTerm : String;
		private var inited:Boolean = false;
		
		
		public function init():void{
			trace("Initializing Search Command");
			model.searchResults = new ArrayCollection();
			inited = true;
		}
		
	
		public function execute(event:PortfolioSearchEvent):AsyncToken {
		if(!inited){
			init();
		}
			searchTerm = event.keywords;
			//search(term);
			return service.GetPortfolios( GUID.USER_GUID,searchTerm,true,true,1 ) as AsyncToken;
		}
		
		/******************************************
		 *  Result handler 
		 */
		public function result(data:Object):void
		{
			var searchCompleteEvent:PortfolioSearchEvent = new PortfolioSearchEvent(PortfolioSearchEvent.SEARCH_COMPLETE, searchTerm);
			//model.searchResults.disableAutoUpdate();
			//model.searchResults.removeAll();
			if ( data.Results != null)
			{
				trace("Seetting the results");
				var arr:Array;
				arr = mx.utils.ArrayUtil.toArray(data.Results)
				for each (var obj:Object in arr )
				{
					model.searchResults.addItem( PortfolioUtil.parsePortfolio(obj));
				}
			}
			else
			{
				trace("SearchCommand: Clearing Results");
				searchTerm = null;
			}
			dispatchEvent(searchCompleteEvent);
		}
		
		/******************************************
		 *  Fault handler in case the request failed. 
		 */
		public function error (fault:FaultEvent, trigger:PortfolioSearchEvent) : void {
			//need to add some logging here
			Alert.show(fault.fault.message,fault.fault.faultDetail);
		}  
		
	
		
		
		
		
	}
}